#include <iostream>
#include <ctime>
#include <pthread.h>
#include <unistd.h>
#include "log.hpp"
#include "ringqueue.hpp"
#include "Task.hpp"

void *Productor(void *args)
{
    ringqueue<Task>* rt = static_cast<ringqueue<Task>*>(args);
    while(true)
    {
        int data1 = rand() % 10; // [1, 10] // 将来深刻理解生产消费，就要从这里入手，TODO
        usleep(rand() % 123);
        int data2 = rand() % 10; // [1, 10] // 将来深刻理解生产消费，就要从这里入手，TODO
        usleep(rand() % 123);
        char oper = opers[rand() % (opers.size())];
        Task t(data1, data2, oper);
        std::cout << "product Task:" << t.PrintTask() << std::endl;
        rt->push(t);
    }
    return NULL;
}

void *Consumer(void *args)
{
    ringqueue<Task>* rq = static_cast<ringqueue<Task>*>(args);
    while(true)
    {
        Task t;
        rq->pop(&t);
        t();//t.run();
        std::cout << "consumer done,data is " << t.PrintResult() << std::endl;
    }
    return NULL;
}

int main()
{
    Log log;
    log.Logmessage(Debug, "hello %d, %s, %f", 10, "bite", 3.14);
    log.Logmessage(Warning, "hello %d, %s, %f", 10, "bite", 3.14);
    log.Logmessage(Error, "hello %d, %s, %f", 10, "bite", 3.14);
    log.Logmessage(Info, "hello %d, %s, %f", 10, "bite", 3.14);
    srand((uint64_t)time(nullptr) ^ pthread_self());
    pthread_t c[3], p[2];

    // 唤醒队列中只能放置整形？？？
    // RingQueue<int> *rq = new RingQueue<int>();
    ringqueue<Task> *rq = new ringqueue<Task>();

    pthread_create(&p[0], nullptr, Productor, rq);
    pthread_create(&p[1], nullptr, Productor, rq);
    pthread_create(&c[0], nullptr, Consumer, rq);
    pthread_create(&c[1], nullptr, Consumer, rq);
    pthread_create(&c[2], nullptr, Consumer, rq);

    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(c[2], nullptr);

    return 0;
}